package com.db.system.config;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import com.db.system.enums.DataSourceType;

/**
 * 配置多数据源(Druid)
 * @Package: com.db.system.config
 * @ClassName: DataSourceConfig.java
 * @Description:配置多数据源(Druid)
 * 
 * @author kaifa008
 * @date 2022年1月18日 下午3:40:44
 * @Copyright: 2022 Copyright (c) 2018 LgSteel
 */
@Configuration
public class DataSourceConfig {
 
    /**
	 * 查看配置文件中数据库连接池主从
	 */
    @Value("${dataSource.dbType}")
	private String dbType;
 
    @Bean(name="MASTER")
    @ConfigurationProperties("spring.datasource.druid.master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name="SLAVE")
    @ConfigurationProperties("spring.datasource.druid.slave")
    public DataSource slaveDataSource() {
        return DataSourceBuilder.create().build();
    }
 
    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dynamicDataSource() {
        if (StringUtils.isEmpty(dbType)) {
			dbType = "SLAVE";
		}
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.SLAVE, slaveDataSource());
        targetDataSources.put(DataSourceType.MASTER, masterDataSource());
		DataSource defaultTargetDataSource = null;
		switch (dbType) {
			case "SLAVE":
				defaultTargetDataSource = (DataSource) targetDataSources.get(DataSourceType.SLAVE);
				break;
    	   	case "MASTER":
    	   		defaultTargetDataSource = (DataSource) targetDataSources.get(DataSourceType.MASTER);
    	   		break;
			default:
				defaultTargetDataSource = (DataSource) targetDataSources.get(DataSourceType.SLAVE);
				break;
		}
//		DynamicDataSource dynamicDataSource = new DynamicDataSource();
//		dynamicDataSource.setDefaultTargetDataSource(defaultTargetDataSource);
//		dynamicDataSource.setTargetDataSources(targetDataSources);
//		return dynamicDataSource;
        return new DynamicDataSource(defaultTargetDataSource, targetDataSources);
    }
}

